"""
File for handling the animation objects. Loading and Rendering done.
"""

from pyglet.gl import *
import data

class Face:
    def __init__(self, ind, uv):
        self.indices = ind 
        self.uv = uv

class KeyFrame:
    def __init__(self, fp, nv):
        self.verts = []
        self.frame_num = int(fp.readline())
        for i in xrange(nv):
            (v1, v2, v3) = fp.readline().split(' ')
            self.verts.append(float(v1)) 
            self.verts.append(float(v2)) 
            self.verts.append(float(v3)) 

class Action:
    def __init__(self, fp, nv):
        (self.name, self.num_frames) = fp.readline().split(' ')
        self.num_frames = int(self.num_frames)
        self.kf = []
        for j in xrange(self.num_frames):
            k = KeyFrame(fp, nv)
            self.kf.append(k)
         
class Model:
    def __init__(self, fname):
        fp = open(fname)
        #load texture and store the texture as member
        texname = fp.readline().strip()      
        self.tex = pyglet.image.load(data.filepath(texname)).get_texture()
        #load the model
        (self.nv, self.nf, self.na) = fp.readline().split(' ')
        self.nv = int(self.nv)
        self.nf = int(self.nf)
        self.na = int(self.na)

        self.faces = []
        for i in xrange(self.nf):
            indx = fp.readline().split(' ')
            uv = []
            for j in xrange(3):
                (s, t) = fp.readline().split(' ')
                uv.append(float(s))
                uv.append(float(t))
            face = Face((int(indx[0]), int(indx[1]), int(indx[2])), uv)
            self.faces.append(face)

        self.acts = []
        for i in xrange(self.na):
            act = Action(fp, self.nv)
            self.acts.append(act)
        fp.close()

class AnimObject:
    def __init__(self):
        self.model = None
        self.act = None
        self.cur_frame = 0

    def loadModel(self, fname):
        pass
   
    def setModel(self, model):
        self.model = model

    def setAction(self, actname):
        if self.act and self.act.name == actname:
            return
        self.act = None
        for i in xrange(self.model.na):
            a = self.model.acts[i]
            if(actname == a.name):
                self.act = a
                self.cur_frame = a.kf[0].frame_num
        if(self.act == None):
            self.act = self.obj.model.acts[0]

    def renderObject(self):
        if(self.cur_frame > self.act.kf[self.act.num_frames-1].frame_num):
            self.cur_frame = self.act.kf[0].frame_num+1

        n_index = 0
        while (self.cur_frame > self.act.kf[n_index].frame_num):
            n_index += 1
        index = n_index - 1

        v = self.act.kf[index].verts
        v1 = self.act.kf[n_index].verts
        t = (self.cur_frame - self.act.kf[index].frame_num)/float(self.act.kf[n_index].frame_num - self.act.kf[index].frame_num)
        
        glBindTexture(GL_TEXTURE_2D, self.model.tex.id)
        glBegin(GL_TRIANGLES)
        for i in xrange(self.model.nf):
            face = self.model.faces[i] 
            for j in xrange(3):
                i1 = face.indices[j] * 3 #3 values per vertex 3 verts per face 
                dv = [ v[i1]+t*(v1[i1]-v[i1]), v[i1+1]+t*(v1[i1+1]-v[i1+1]), v[i1+2]+t*(v1[i1+2]-v[i1+2]) ]
                glTexCoord2f(face.uv[j*2], face.uv[j*2+1]) #2 tex coords per vertex
                glVertex3f(dv[0], dv[1], dv[2])
        glEnd()

#simple polygon drawing object
class SimplePolygon:
    def __init__(self, pos=[0, 0, 0]):
        self.verts = ()
        self.pos = pos
        pass

    def sphereCollide(self, point, r2):
        """Returns 1 if colliding 0 if not colliding"""
    #do a sphere bounding collision
    #distance between two points should be > r1 + r2
        p = self.pos
        p1 = point
        r1 = 5 
        d2 = (p[0] - p1[0]) * (p[0]-p1[0]) + (p[1]-p1[1])*(p[1]-p1[1]) + (p[2]-p1[2])*(p[2]-p1[2])
        if d2 < (r1*r1 + r2*r2):
            return True
        return False

    def renderObject(self, p1, p2):
        p4 = (p1[0], p1[1], p1[2]+5)
        p3 = (p2[0], p2[1], p2[2]+5)
        self.verts = p1 + p2
        
        self.verts += p4
        self.verts += p3

        glColor3f(1, 0, 0)
        pyglet.graphics.draw(len(self.verts)/3, pyglet.gl.GL_QUAD_STRIP, ('v3f', self.verts))

